import type { CardItem } from '../types/cardData';
import { generateSnowflakeId } from '../utils/snowflake';
import { getConfig } from './configService';
import * as localService from './localService';  // 取消注释此导入
import { 
  fetchRemoteCards,
  getRemoteCard,
  saveRemoteCard,
  deleteRemoteCard, 
  batchDeleteRemoteCards 
} from './remoteService';

export interface CardResponse {
  items: CardItem[];
  hasMore: boolean;
  total: number;
}

// 获取当前数据源类型
async function getDataSourceType(): Promise<'local' | 'remote'> {
  const config = await getConfig();
  return config.dataSource.type;
}

// 获取卡片列表
export async function fetchCards(page: number, pageSize: number): Promise<CardResponse> {
  const dataSourceType = await getDataSourceType();
  
  if (dataSourceType === 'remote') {
    // 使用远程数据源
    return fetchRemoteCards(page, pageSize);
  } else {
    // 使用本地数据源
    return localService.fetchLocalCards(page, pageSize);
  }
}

// 保存卡片
export async function saveCard(card: Partial<CardItem>): Promise<CardItem> {
  // Generate snowflake ID if this is a new card
  if (!card.id) {
    card.id = generateSnowflakeId();
  }
  
  const dataSourceType = await getDataSourceType();
  
  if (dataSourceType === 'remote') {
    // 使用远程数据源
    return saveRemoteCard(card);
  } else {
    // 使用本地数据源
    return localService.saveLocalCard(card);
  }
}

// 删除卡片
export async function deleteCard(cardId: string): Promise<boolean> {
  const dataSourceType = await getDataSourceType();
  
  if (dataSourceType === 'remote') {
    // 使用远程数据源
    return deleteRemoteCard(cardId);
  } else {
    // 使用本地数据源
    return localService.deleteLocalCard(cardId);
  }
}

// 批量删除卡片
export async function batchDeleteCards(cardIds: string[]): Promise<{ success: boolean; count: number }> {
  try {
    const dataSourceType = await getDataSourceType();
    
    if (dataSourceType === 'remote') {
      // 使用远程数据源
      return batchDeleteRemoteCards(cardIds);
    } else {
      // 使用本地数据源
      return localService.batchDeleteLocalCards(cardIds);
    }
  } catch (error) {
    console.error('批量删除卡片失败:', error);
    return {
      success: false,
      count: 0
    };
  }
}

// 获取单个卡片
export async function getCard(cardId: string): Promise<CardItem | null> {
  const dataSourceType = await getDataSourceType();
  
  if (dataSourceType === 'remote') {
    // 使用远程数据源
    return getRemoteCard(cardId);
  } else {
    // 使用本地数据源
    return localService.getLocalCard(cardId);
  }
}